package cn.iocoder.boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.boot.common.RedisKeyConstants;
import cn.iocoder.boot.dto.KbPlatformApiDTO;
import cn.iocoder.boot.entity.KbPlatformApi;
import cn.iocoder.boot.mapper.KbPlatformApiMapper;
import cn.iocoder.boot.service.KbPlatformApiService;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.serviceException;
import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;

@Service
@DS("master")
@Slf4j
public class KbPlatformApiServiceImpl extends ServiceImpl<KbPlatformApiMapper, KbPlatformApi> implements KbPlatformApiService {


    @Resource
    private KbPlatformApiMapper kbPlatformApiMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean addOrUpdate(KbPlatformApiDTO platformApiDTO) {
        String redisKey = String.format(RedisKeyConstants.PLATFORM_API_TEMPLATE, platformApiDTO.getUserId());

        KbPlatformApi kbPlatformApi = new KbPlatformApi();
        BeanUtil.copyProperties(platformApiDTO, kbPlatformApi);
        //预警值计算
        kbPlatformApi.setAlarmValue((platformApiDTO.getCallNumber() * (1 - (platformApiDTO.getAlarmThreshold() / 100))));
        kbPlatformApi.setRemainingNumber(platformApiDTO.getCallNumber());
        //查询这个用户是否已存在
        if (Objects.isNull(kbPlatformApi.getId())){
            KbPlatformApi kbPlatformApiByUserId = kbPlatformApiMapper.selectByUserId(platformApiDTO.getUserId());
            if (Objects.nonNull(kbPlatformApiByUserId)) {
                throw serviceException(String.format("此账号已使用在授权平台：%s，请更换或新建用户", kbPlatformApiByUserId.getUserName()));
            }
        }
        if (Objects.isNull(kbPlatformApi.getId())) {
            kbPlatformApiMapper.insert(kbPlatformApi);

        } else {
            kbPlatformApiMapper.updateById(kbPlatformApi);
        }
        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(kbPlatformApi), 2, TimeUnit.DAYS);
        return true;
    }

    @Override
    public boolean del(Long id) {
        KbPlatformApi kbPlatformApi = new KbPlatformApi();
        kbPlatformApi.setId(id);
        //删除缓存
        KbPlatformApi platformApi = kbPlatformApiMapper.selectById(id);
        if (Objects.nonNull(platformApi)) {
            String redisKey = String.format(RedisKeyConstants.PLATFORM_API_TEMPLATE, platformApi.getUserId());
            stringRedisTemplate.delete(redisKey);
        }

        return kbPlatformApiMapper.deleteById(kbPlatformApi) > 0;
    }

    @Override
    public KbPlatformApi getPlatformApi(Long id) {
        String redisKey = String.format(RedisKeyConstants.PLATFORM_API_TEMPLATE, id);
        KbPlatformApi kbPlatformApi = JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), KbPlatformApi.class);
        if (Objects.isNull(kbPlatformApi)) {
            //查询数据库
            kbPlatformApi = kbPlatformApiMapper.selectByUserId(id);
            if (Objects.isNull(kbPlatformApi)) {
                throw serviceException("账号不存在或者当日次数已用完，请联系管理员");
            }
            //设置缓存
            stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(kbPlatformApi), 2, TimeUnit.DAYS);
        }
        return kbPlatformApi;
    }

    @Override
    public KbPlatformApi getPlatformApiById(Long id) {
        return kbPlatformApiMapper.selectById(id);
    }

    @Override
    public Page<KbPlatformApiDTO> getPlatformApiPage(KbPlatformApiDTO platformApiDTO) {
        Page<KbPlatformApi> page = new Page<>(platformApiDTO.getPageNo(), platformApiDTO.getPageSize());
//        LambdaUpdateWrapper<KbPlatformApi> wrapper = Wrappers.lambdaUpdate();
//        wrapper.eq(KbPlatformApi::getDeleted, false);
//        if (Objects.nonNull(platformApiDTO.getUserName())){
//
//        }
        return kbPlatformApiMapper.selectPageList(page, platformApiDTO);
    }
}
